package org.qiyu.live.living.provider.config;

import jakarta.annotation.Resource;
import org.idea.qiyu.live.framework.redis.starter.key.LivingProviderCacheKeyBuilder;
import org.qiyu.live.living.interfaces.constants.LivingRoomTypeEnum;
import org.qiyu.live.living.interfaces.dto.LivingRoomRespDTO;
import org.qiyu.live.living.provider.service.ILivingRoomService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 定时任务，往redis 中存入直播间列表 每分钟同步一次
 * @Author: 张广焱
 * @Date: 2024-06-03 下午8:14
 */
@Configuration
public class RefreshLivingRoomListJob implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(RefreshLivingRoomListJob.class);
    @Resource
    private ILivingRoomService livingRoomService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private LivingProviderCacheKeyBuilder cacheKeyBuilder;

    private ScheduledThreadPoolExecutor schedulePool = new ScheduledThreadPoolExecutor(1);

    @Override
    public void afterPropertiesSet() throws Exception {
        schedulePool.scheduleWithFixedDelay(new RefreshCacheListJob(), 3000, 60000, TimeUnit.MILLISECONDS);
    }

    private class RefreshCacheListJob implements Runnable {
        @Override
        public void run() {
            //获取key
            String cachKey = cacheKeyBuilder.buildRefreshLivingRoomListLock();
            Boolean lockStats = redisTemplate.opsForValue().setIfAbsent(cachKey, 1, 1, TimeUnit.SECONDS);
            if (lockStats) {
                logger.debug("[RefreshLivingRoomListJob] starting 加载db中记录的直播间进redis里");
                refreshDBToRedis(LivingRoomTypeEnum.DEFAULT_LIVING_ROOM.getCode());
                refreshDBToRedis(LivingRoomTypeEnum.PK_LIVING_ROOM.getCode());
                logger.debug("[RefreshLivingRoomListJob] end 加载db中记录的直播间进redis里");
            }
        }

        private void refreshDBToRedis(Integer type) {
            String cacheKey = cacheKeyBuilder.buildLivingRoomList(type);
            //获取db中直播间列表
            List<LivingRoomRespDTO> resultList = livingRoomService.listAllLivingRoomFromDB(type);
            if (CollectionUtils.isEmpty(resultList)) {
                redisTemplate.delete(cacheKey);
                return;
            }
            String tempListName = cacheKey + "_temp";
            resultList.forEach(e -> {
                redisTemplate.opsForList().rightPush(tempListName, e);
            });
            //防止io占用
            redisTemplate.rename(tempListName, cacheKey);
            redisTemplate.delete(tempListName);
        }
    }
}
